//
//  ELSearchViewModel.swift
//  WZApp
//
//  Created by evol on 2018/7/2.
//  Copyright © 2018年 evol. All rights reserved.
//

import UIKit
import RxCocoa
import RxSwift

class ELSearchViewModel {

    var datas: Observable<[ELTagModel]>?
    
    let closeCommand = PublishSubject<Bool>()
    
    let locationCommand = PublishSubject<ELTagModel>()
    
    let navigationCommand = PublishSubject<ELTagModel>()
    
    var searchInput: Observable<String>?
    {
        didSet{
            datas = AppCommonData.share.tagModels.flatMap(filterResult)
                .subscribeOn(ConcurrentDispatchQueueScheduler(qos: DispatchQoS.userInitiated)) //后台线程序列
                .observeOn(MainScheduler.instance) //主线程监听
                .asObservable()
        }
    }
    
    init() {
    }
    
    func filterResult(data:[ELTagModel])
        -> Observable<[ELTagModel]> {
            return searchInput!
                .debounce(0.5, scheduler: MainScheduler.instance) //只有间隔超过0.5秒才发送
                .flatMapLatest{
                    query -> Observable<[ELTagModel]> in
                    //输入条件为空，则直接返回原始数据
                    if query.isEmpty{
                        return Observable.just(data)
                    }else{
                        var newData:[ELTagModel] = []
                        for model in data {
                            if (model.name?.contains(query))! {
                                newData.append(model)
                            }else if (model.name?.el_pinyin.contains(query))! {
                                newData.append(model)
                            }
                        }
                        return Observable.just(newData)
                    }
            }
    }

}
